﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Web.Profile;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

using Continental.Code.BL;
using Continental.Code.Entity;

namespace Continental.Admin
{
    public partial class ManagerTuDiemAddNew : System.Web.UI.Page
    {
        public String message = "";
        public Int32 tuDiemID = -1;
        public String email = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            // trường hợp thêm mới

            if (!Page.IsPostBack)
            {
                LoadNhomTuDiemLevel0();
                LoadQuanHuyen();
                this.ddlNhomTuDiemLevel1.Enabled = false;
                this.ddlDuongPho.Enabled = false;

                if (Request.QueryString["Email"] != null)
                {
                    ViewState["ID"] = null;
                    ViewState["ACTION"] = "ADD";
                    this.btnSave.Text = "Thêm mới";
                    this.btnDelete.Enabled = false;
                    this.ltlStatus.Text = "Thêm mới";
                }
                else if (Request.QueryString["TuDiemID"] != null)
                {
                    tuDiemID = Int32.Parse(Request.QueryString["TuDiemID"].ToString());
                    ViewState["ID"] = tuDiemID;
                    ViewState["ACTION"] = "UPDATE";
                    this.btnSave.Text = "Cập nhật";
                    Code.Entity.TuDiem theTuDiem = TuDiemProvider.GetTuDiemByID(tuDiemID);
                    if (theTuDiem != null)
                    {
                        this.ltlStatus.Text = "Bạn đang sửa thông tin : " + theTuDiem.Name;
                        // thông tin cơ bản
                        this.txtAddress.Text = theTuDiem.Address;
                        this.txtEmail.Text = theTuDiem.Email;
                        this.txtMobile.Text = theTuDiem.MobiPhone;
                        this.txtName.Text = theTuDiem.Name;
                        this.txtShortDescription.Text = theTuDiem.ShortDescription;
                        this.fckDescription.Value = theTuDiem.Description;
                        this.txtHomePhone.Text = theTuDiem.NumberPhone;
                        this.txtTitleOrName.Text = theTuDiem.TitleOrName;
                        this.txtWebsite.Text = theTuDiem.Website;
                        this.ckDeletedFlag.Checked = theTuDiem.DeletedFlag;
                        this.ckVip.Checked = theTuDiem.IsVip;
                        this.txtNumberOfRating.Text = theTuDiem.LevelOfRanging.ToString();
                        ViewState["IMAGE"] = theTuDiem.ImageUrl; // ảnh đại diện
                        ViewState["USER_ID"] = theTuDiem.UserId;
                        //load đường phố
                        this.ddlDuongPho.Enabled = true;
                        this.ddlDuongPho.DataSource = ExtensionProvider.GetDuongPhoList(theTuDiem.QuanHuyenID);
                        ddlDuongPho.DataBind();
                        this.ddlDuongPho.SelectedValue = theTuDiem.DuongPhoID.ToString();
                        // Load nhóm Tụ Điểm
                        NhomTuDiem theNhomTuDiem = TuDiemProvider.GetNhomTuDiemByID(theTuDiem.QuanHuyenID);

                        //Trường hợp là nhóm cha
                        if (theNhomTuDiem.ParentID == 0)
                        {
                            ddlNhomTuDiemLevel0.SelectedValue = theTuDiem.NhomID.ToString();
                        }
                        else
                        {
                            ddlNhomTuDiemLevel0.SelectedValue = theNhomTuDiem.ParentID.ToString();
                            //load phân loại nhóm tụ điểm
                            this.ddlNhomTuDiemLevel1.DataSource = TuDiemProvider.GetNhomTuDiemByParentID(theNhomTuDiem.ParentID);
                            this.ddlNhomTuDiemLevel1.DataBind();
                            this.ddlNhomTuDiemLevel1.SelectedValue = theTuDiem.NhomID.ToString();
                            this.ddlNhomTuDiemLevel1.Enabled = true;
                        }

                    }
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("ManagerTuDiem.aspx");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            String action = ViewState["ACTION"].ToString();
            Page.Validate("CAPNHAT");

            if (Page.IsValid)
            {
                if (!ValidateControl())
                    return;

                Code.Entity.TuDiem theTuDiem = new Code.Entity.TuDiem();

                if (ddlNhomTuDiemLevel1.Enabled == false)
                {
                    theTuDiem.NhomID = Int32.Parse(this.ddlNhomTuDiemLevel0.SelectedValue);
                }
                else
                {
                    theTuDiem.NhomID = Int32.Parse(this.ddlNhomTuDiemLevel1.SelectedValue);
                }

                theTuDiem.QuanHuyenID = Int32.Parse(this.ddlQuanHuyen.SelectedValue);
                theTuDiem.DuongPhoID = Int32.Parse(this.ddlDuongPho.SelectedValue);
                theTuDiem.Address = this.txtAddress.Text;
                theTuDiem.ToaDo = this.txtToaDo.Text.Trim();
                theTuDiem.Description = this.fckDescription.Value;
                theTuDiem.CityID = 1;
                theTuDiem.DescriptionSign = Code.Utility.HelpMethod.RemoveHtmlTag(Server.HtmlDecode(theTuDiem.Description));
                theTuDiem.DescriptionNotSign = Code.Utility.HelpMethod.RemoveSign4VietnameseString(theTuDiem.DescriptionSign);
                theTuDiem.Email = this.txtEmail.Text;
                theTuDiem.MobiPhone = this.txtMobile.Text;
                theTuDiem.Name = this.txtName.Text;
                theTuDiem.NumberPhone = this.txtHomePhone.Text;
                theTuDiem.ShortDescription = this.txtShortDescription.Text;
                theTuDiem.TitleOrName = this.txtTitleOrName.Text;
                theTuDiem.Website = this.txtWebsite.Text;
                theTuDiem.IsVip = this.ckVip.Checked;

                try
                {
                    theTuDiem.LevelOfRanging = Int32.Parse(this.txtNumberOfRating.Text.Trim());
                }
                catch
                {
                    theTuDiem.LevelOfRanging = 1;
                }

                theTuDiem.DeletedFlag = this.ckDeletedFlag.Checked;

                if (this.fuImage.HasFile)
                {
                    String pathAvatars = Server.MapPath("~/");
                    try
                    {
                        String newFileName = DateTime.Now.Ticks.ToString() + ".gif";
                        int thumbWidth = 120;
                        int thumbHeight = 100;

                        System.Drawing.Image oImg = System.Drawing.Image.FromStream(fuImage.PostedFile.InputStream);
                        System.Drawing.Image oThumbNail = new Bitmap(thumbWidth, thumbHeight, oImg.PixelFormat);

                        Graphics oGraphic = Graphics.FromImage(oThumbNail);
                        oGraphic.CompositingQuality = CompositingQuality.HighQuality;
                        oGraphic.SmoothingMode = SmoothingMode.HighQuality;
                        oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                        Rectangle oRectangle = new Rectangle(0, 0, thumbWidth, thumbHeight);
                        oGraphic.DrawImage(oImg, oRectangle);

                        oThumbNail.Save(pathAvatars + "\\ImageData\\TuDiem\\" + newFileName, ImageFormat.Gif);
                        theTuDiem.ImageUrl = newFileName;
                        oImg.Dispose();
                    }
                    catch (Exception ex)
                    {
                        message += "Error: " + ex.Message;
                        return;
                    }
                }
                else
                {
                    theTuDiem.ImageUrl = ViewState["IMAGE"].ToString();
                }

                if (action.Equals("ADD"))
                {
                    MembershipUser theUser = Membership.GetUser(Request.QueryString["Email"].ToString());
                    if (theUser == null)
                    {
                        message += "Email chủ quản chưa tồn tại trong Hệ Thống";
                        return;
                    }
                    theTuDiem.UserId = theUser.ProviderUserKey.ToString();
                    TuDiemProvider.InsertTuDiem(theTuDiem);
                    Response.Redirect("ManagerTuDiem.aspx");
                    message += "Thêm mới thành công";
                }
                else
                {
                    theTuDiem.TuDiemID = Int32.Parse(ViewState["ID"].ToString());
                    theTuDiem.UserId = ViewState["USER_ID"].ToString();
                    TuDiemProvider.UpdateTuDiemByID(theTuDiem);
                    Response.Redirect("ManagerTuDiem.aspx");
                    message += "Cập nhật thành công";
                }
            }
        }

        private System.Drawing.Image Bitmap(int thumbWidth, int thumbHeight, PixelFormat pixelFormat)
        {
            throw new NotImplementedException();
        }

        private bool ValidateControl()
        {
            bool flag = true;

            if (this.ddlNhomTuDiemLevel0.SelectedValue == "-1")
            {
                message += "Hãy chọn Nhóm Tụ Điểm" + "<br />";
                flag = false;
            }

            if (this.ddlNhomTuDiemLevel1.SelectedValue == "-1" && this.ddlNhomTuDiemLevel1.Enabled == true)
            {
                message += "Hãy chọn Phân Loại Nhóm Tụ Điểm" + "<br />";
                flag = false;
            }

            if (this.ddlQuanHuyen.SelectedValue == "-1")
            {
                message += "Hãy chọn Quận Huyện" + "<br />";
                flag = false;
            }

            if (this.ddlDuongPho.SelectedValue == "-1")
            {
                message += "Hãy chọn Đường Phố" + "<br />";
                flag = false;
            }

            if (!this.fuImage.HasFile && ViewState["ACTION"].ToString() == "ADD")
            {
                message += "Hãy chọn ảnh hiển thị" + "<br />";
                flag = false;
            }

            return flag;
        }

        private void LoadNhomTuDiemLevel0()
        {
            ddlNhomTuDiemLevel0.DataSource = TuDiemProvider.GetNhomTuDiemByParentID(0);
            ddlNhomTuDiemLevel0.DataBind();
        }

        private void LoadQuanHuyen()
        {
            this.ddlQuanHuyen.DataSource = ExtensionProvider.GetQuanHuyenList();
            ddlQuanHuyen.DataBind();
        }

        protected void ddlNhomTuDiemLevel0_DataBound(object sender, EventArgs e)
        {
            ListItem li = new ListItem("chọn nhóm Tụ Điểm...", "-1");
            this.ddlNhomTuDiemLevel0.Items.Insert(0, li);
        }

        protected void ddlNhomTuDiemLevel1_DataBound(object sender, EventArgs e)
        {
            ListItem li = new ListItem("chọn phân loại nhóm...", "-1");
            this.ddlNhomTuDiemLevel1.Items.Insert(0, li);
        }

        protected void ddlNhomTuDiemLevel0_SelectedIndexChanged(object sender, EventArgs e)
        {
            Int32 nhomTuDiemLevel0 = Int32.Parse(this.ddlNhomTuDiemLevel0.SelectedValue);
            DataSet dsResult = TuDiemProvider.GetNhomTuDiemByParentID(nhomTuDiemLevel0);
            this.ddlNhomTuDiemLevel1.DataSource = dsResult;
            ddlNhomTuDiemLevel1.DataBind();

            if (dsResult.Tables[0].Rows.Count == 0)
            {
                this.ddlNhomTuDiemLevel1.Enabled = false;

            }
            else
            {
                this.ddlNhomTuDiemLevel1.Enabled = true;
            }
        }

        protected void ddlQuanHuyen_DataBound(object sender, EventArgs e)
        {
            ListItem li = new ListItem("chọn Quận Huyện...", "-1");
            this.ddlQuanHuyen.Items.Insert(0, li);
        }

        protected void ddlQuanHuyen_SelectedIndexChanged(object sender, EventArgs e)
        {
            Int32 quanHuyenID = Int32.Parse(this.ddlQuanHuyen.SelectedValue);
            this.ddlDuongPho.DataSource = ExtensionProvider.GetDuongPhoList(quanHuyenID);
            ddlDuongPho.DataBind();
            this.ddlDuongPho.Enabled = true;
        }

        protected void ddlDuongPho_DataBound(object sender, EventArgs e)
        {
            ListItem li = new ListItem("chọn Đường Phố...", "-1");
            this.ddlDuongPho.Items.Insert(0, li);
        }
    }
}
